/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2022-11-30 11:27:09
 * @LastEditors: 周海 zhouhaib@yonyou.com
 * @LastEditTime: 2022-12-14 18:30:04
 */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
    addPost,
    delPost,
    getPost,
    updatePost,
} from '@/api/system/post';
import { addPostMenu, delPostMenuByPostId } from '@/api/system/postMent';
import BillCard from '@/components/BillCard';
import { useStore } from '@/store';
import { SysPostDomain } from '@/type.d/system/post';
import { SysPostMenuDomain } from '@/type.d/system/postMenu';
import { SysRolePostDomain } from '@/type.d/system/rolePost';
import { ProFormColumnsType, ProFormInstance } from '@ant-design/pro-components';
import { Space, Button, Modal, Tabs, Form, Row, Col, Input, InputNumber, Radio, DatePicker } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react'
import KeepAlive from 'react-activation';
import PostMenu from './components/postMenu';
import PostRole from './components/postRole';
import TreeTransfer from './components/treeTransfer';
import './index.less';

interface PostCardProp {
    sysNormalDisableOptions: any[];
    /**
     * 卡片数据 受控
     */
    cardData: SysPostDomain;
    /**
     * 卡片新增时的默认数据
     */
    newdata?: SysPostDomain;
    /**
     * 列表数据
     */
    tableListDataSource: SysPostDomain[];
    /**
     * 更新列表数据
     */
    setTableListDataSource: (data: SysPostDomain[]) => void;

    setIsedit?: (isedit: boolean) => void;

    isedit?: boolean;
    /**
     * 跳转到列表状态
     */
    onBack?: (e?: React.MouseEvent<HTMLElement>) => void;
}
export type PostCardInstance = {
    setIsedit: (isedit: boolean) => void
}
type PostCardRef = React.MutableRefObject<PostCardInstance | undefined> | React.RefObject<PostCardInstance | undefined>

const PostCard = forwardRef((props: PostCardProp) => {
    const { sysNormalDisableOptions, cardData, newdata = {}, tableListDataSource, setTableListDataSource, setIsedit, isedit = false, onBack } = props;
    const { layoutStore, userStore } = useStore();
    const [selectdata, setSelectdata] = useState<SysPostDomain>(cardData);
    const [formRef] = Form.useForm<SysPostDomain>();


    const [oldSelectdata, setOldSelectdata] = useState<SysPostDomain>();//编辑状态临时保存选中的数据

    const [isModalOpen, setIsModalOpen] = useState<boolean>(false);//菜单分配界面弹窗

    const [postRoles, setPostRoles] = useState<SysRolePostDomain[]>([]);//关联的角色信息
    const [postMenus, setPostMenus] = useState<SysPostMenuDomain[]>([]);//关联的菜单信息
    const [menus, setMenus] = useState<any[]>([]);//s所有菜单数据

    const [activeKey, setActiveKey] = useState<string>('1');


    const intCardData = (_cardData: SysPostDomain) => {
        if (_cardData.postId) {
            layoutStore.OpenSpanning()
            getPost(_cardData.postId).then((res) => {
                const info = res.data;
                setSelectdata({ ...info.datas })
                setOldSelectdata({ ...info.datas })
                setPostRoles(info.postroles)
                setMenus(info.menus)
                setPostMenus(info.postmenus)
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }


    const addCardData = (_cardData: SysPostDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const editCardData = () => {
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const resetCardData = () => {
        setSelectdata({ ...oldSelectdata })
        setOldSelectdata({})
    }

    const onDelete = (dedata: SysPostDomain) => {
        if (dedata.pkPost) {
            layoutStore.OpenSpanning()
            delPost(dedata.pkPost).then(() => {
                setSelectdata({})
                setOldSelectdata({})
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.pkPost !== dedata.pkPost
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }
    }

    useEffect(() => {//从列表跳转到卡片，如果数据发生了变化，更新数据
        intCardData(cardData)
    }, [cardData])


    useEffect(() => {
        formRef.resetFields()
        if (selectdata) {
            formRef.setFieldsValue({ ...selectdata });
        } else {
            formRef.setFieldsValue({});
        }
    }, [selectdata])
    /**
     * 表单字段配置
     */
    const cardItems: JSX.Element =
        <Row>
            <Col md={8} xl={6} hidden>
                <Form.Item name="postId" label="岗位ID">
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="postCode" label="岗位编码" rules={[{
                    required: true,
                    message: '请输入岗位编码',
                },]}>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="postName" label="岗位名称" rules={[{
                    required: true,
                    message: '请输入岗位名称',
                },]}>
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="postSort" label="显示顺序" rules={[{
                    required: true,
                    message: '请输入显示顺序',
                },]}>
                    <InputNumber decimalSeparator={'0'} />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="status" label="状态">
                    <Radio.Group options={sysNormalDisableOptions} />
                </Form.Item>
            </Col>
            <Col md={24} xl={24}>
                <Form.Item name="remark" label="备注">
                    <Input.TextArea />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="createBy" label="创建者">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="dateTime" label="创建时间">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="updateBy" label="更新者">
                    <Input disabled />
                </Form.Item>
            </Col>
            <Col md={8} xl={6}>
                <Form.Item name="updateTime" label="更新时间">
                    <Input disabled />
                </Form.Item>
            </Col>
        </Row>;

    const cardbuttons = (
        <Space>
            <Button
                hidden={!userStore.hasPerms('system:corp:add')}
                size='small'
                key="add"
                type="primary"
                onClick={() => {
                    addCardData({ ...newdata })
                }}
            >
                新增
            </Button>
            <Button
                hidden={!userStore.hasPerms('system:corp:edit')}
                size='small'
                key="edit"
                type="primary"
                disabled={selectdata?.postId ? false : true}
                onClick={() => {
                    editCardData()
                }}
            >
                修改
            </Button>
            <Button
                hidden={!userStore.hasPerms('system:corp:delete')}
                size='small'
                key="delete"
                type="primary"
                disabled={selectdata?.postId ? false : true}
                onClick={() => {
                    Modal.confirm({
                        okText: '确定',
                        cancelText: '取消',
                        title: '系统提示',
                        content: '确定要删除数据吗？',
                        type: 'warning',
                        onOk: () => {
                            onDelete(selectdata)
                        }
                    }
                    )

                }}
            >
                删除
            </Button>
        </Space>
    )

    const onSave = () => {
        formRef.validateFields().then((data) => {
            if (!selectdata.pkPost) {//新增
                layoutStore.OpenSpanning()
                addPost({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据

                    tableListDataSource.push(res.data)
                    setTableListDataSource([...tableListDataSource])//更新列表数据

                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            } else {//更新
                layoutStore.OpenSpanning()
                updatePost({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    //更新列表数据
                    setTableListDataSource(tableListDataSource.map((item) => {
                        if (item.pkPost === res.data.pkPost) {
                            return res.data
                        } else {
                            return item
                        }
                    }))
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            }
        })

    }

    const editbuttions = (<Space>
        <Button
            size='small'
            key="save"
            type="primary"
            onClick={() => {
                onSave()
            }}
        >
            保存
        </Button>
        <Button
            size='small'
            key="cancel"
            type="primary"
            onClick={() => {
                resetCardData()
                setIsedit?.(false)
            }}
        >
            取消
        </Button>
    </Space>)

    const operations = () => {
        if (activeKey === '1') {
            return <Button size='small'
                key="add"
                type="primary"
                onClick={() => { setIsModalOpen(true) }}>分配菜单</Button>
        }
    }

    const transSave = (targetKeys: string[]) => {
        layoutStore.OpenSpanning()

        //岗位与菜单分配关系
        const postMenus = targetKeys.map((key) => {
            return {
                postId: selectdata.postId,
                menuId: key
            }
        })

        if (postMenus && postMenus.length > 0) {
            addPostMenu(postMenus).then((res) => {
                setPostMenus(res.data)
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        } else {
            //调用删除，清空分配的数据
            if (selectdata.postId) {
                delPostMenuByPostId(selectdata.postId).then(() => {
                    setPostMenus([])
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            }

        }
        setIsModalOpen(false)
    }

    return (
        <>
            <BillCard
                formid='postId'
                key={'postCard'}
                cardItem={cardItems}
                formRef={formRef}
                isedit={isedit}
                extraButton={isedit ? editbuttions : cardbuttons}
                onBack={onBack}
                title={'岗位管理'} >
                {
                    <Tabs
                        defaultActiveKey="1"
                        onChange={setActiveKey}
                        tabBarExtraContent={operations()}
                        items={[
                            {
                                label: `已分配菜单`,
                                key: '1',
                                style: { flex: 1 },
                                children: <PostMenu dataSources={postMenus.map((item) => {
                                    return menus.find((menu) => menu.key === item.menuId)
                                })}></PostMenu>
                            },
                            {
                                label: `已关联角色`,
                                key: '2',
                                children: <PostRole dataSources={postRoles}></PostRole>
                            }
                        ]} />
                }
            </BillCard>
            <TreeTransfer
                dataSource={menus}
                targetKeys={postMenus.map((item) => {
                    return item.menuId || ''
                })}
                isModalOpen={isModalOpen}
                onOk={transSave}
                onCancel={() => setIsModalOpen(false)} />

        </>
    )
})
export default PostCard;